import ButtonToTop from "@/components/composite/Rollup"
import styled from "@emotion/styled"
import { useSize } from "ahooks"
import { useAtom } from "jotai"
import { useMemo, useRef } from "react"
import { Outlet, useParams } from "react-router-dom"
import { homeGamesAtom } from "@/features/business/HomePage_deprecated/atoms_deprecated"
import { BannersSpin } from "./components/BannersSpin"
import { CategoryMenu } from "./components/CategoryMenu"
import { HomeHeader } from "./components/HomeHeader"
import { useOpacity } from "./hooks/useOpacity"

const Root = styled.div`
    font-family: Gilroy;
    font-size: 12rem;
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #f5f5f5;
    &::before {
        font-family: "Roboto Mono";
        content: "ov: ${__APP_VERSION__}";
        position: absolute;
        top: 0;
        right: 2rem;
        font-size: 10rem;
        color: #000;
        opacity: 0.5;
        font-weight: 600;
        z-index: 1000;
    }
`

const TopSection = styled.div<{ $isForYou: boolean; $opacity: number }>`
    position: sticky;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 9;
    background-color: rgba(
        255,
        255,
        255,
        ${({ $opacity, $isForYou }) => ($isForYou ? $opacity : 0.8)}
    );
`
const BannersSpinStyled = styled.div<{ mt: number }>`
    margin-top: ${({ mt }) => `-${mt}rem`};
`
const LinearStyled = styled.div`
    display: flex;
    flex-direction: column;
    flex: 1;
    position: relative;
    z-index: 1;
`

export default function HomePage() {
    const { categoryId = "" } = useParams<{ categoryId: string }>()
    const isForYou = useMemo(() => categoryId === "", [categoryId])
    const [{ banners = [] }] = useAtom(homeGamesAtom)
    const { opacity } = useOpacity()
    // 动态计算顶部导航的高度
    const topSectionRef = useRef<HTMLDivElement>(null)
    const topSectionSize = useSize(topSectionRef)

    // 游戏分类
    if (
        location.pathname.startsWith("/s-game/sections") ||
        location.pathname.startsWith("/s-game/provider")
    ) {
        return (
            <>
                <Root>
                    <Outlet />
                </Root>
                <ButtonToTop />
            </>
        )
    }

    return (
        <>
            <Root>
                <LinearStyled>
                    <TopSection
                        ref={topSectionRef}
                        $isForYou={isForYou}
                        $opacity={opacity}
                    >
                        <HomeHeader />
                        <CategoryMenu />
                    </TopSection>
                    {isForYou && (
                        <BannersSpinStyled mt={topSectionSize?.height || 120}>
                            <BannersSpin list={banners} />
                        </BannersSpinStyled>
                    )}
                    <Outlet />
                </LinearStyled>
            </Root>
            <ButtonToTop />
        </>
    )
}
